# encoding:utf-8

from django.shortcuts import render
from django.http import HttpResponse
import json
from django.contrib.auth.models import User
# Create your views here.
from models import HookModel,UserCarModel,WashSessionModel,CarWashLocalModel,CustomerModel,OrderModel,models,\
     MealModel,CouponModel,CarBrandModel,CarModelModel,ZKOtherLog,ZKWashLog
import qrcode
from io import BytesIO
from django.conf import settings
from django.utils import timezone
from ex import get_or_none
from ex import hook_all
from django.views.decorators.csrf import csrf_exempt
import urlparse
from django.contrib.auth import authenticate, login
import time
from helpers.director.db_tools import sim_dict
import base64
import pay
from django.db import transaction
import re
from django.utils.datastructures import MultiValueDictKeyError
from django.core.paginator import Paginator
from sms import SMS
from ex import redis_conn,get_random_word,distance,session_to_user
import meals
import math
import zk_fake

def get_argument(request):
    if request.method=='POST':
        dc =urlparse.parse_qs(request.body)
        for k,v in dc.items():
            if isinstance(v,list):
                dc[k]=v[0]
        return dc
    else:
        return request.GET


def main_page(request):
    return render(request,'mainpage.html')

def zk_fake_page(request):
    ctx=zk_fake.get_context()
    return render(request,'zk_fake.html',context=ctx)

def hook(request):
    head=request.META
    body = request.body
    path =request.get_full_path()
    method= request.method
    HookModel.objects.create(head=head,body=body,path=path,method=method)
    return HttpResponse(json.dumps({'status':'success'}),content_type="application/json")

@csrf_exempt
@hook_all
def new_session(request):
    if request.method=='GET':
        chepai=request.GET.get('chepai')
        order_key = request.GET.get('order_key')
        zk_no=request.GET.get('zk')
    else:
        dc=json.loads(request.body)
        chepai=dc.get('chepai')
        order_key = dc.get('order_key')
        zk_no=dc.get('zk')        
    try:
        zk = CarWashLocalModel.objects.get(no=zk_no)
        if chepai:
            redis_conn.set('__last_car_no_'+zk_no,chepai,ex=60*5)
            # customer=get_or_none(User,usercarmodel__car_no=chepai)
            #orders = OrderModel.objects.filter(user__usercarmodel__car_no=chepai,status='valid')
            car = UserCarModel.objects.get(car_no=chepai)
            order =meals.consume_chepai(chepai)
            
        elif order_key:
            order = meals.consume_order_key(order_key)
            car = order.car
            
            #orders = OrderModel.objects.filter(pk=order_id,status='valid')

        session=WashSessionModel.objects.create(order=order,zk=zk,car=car)
        dc={
            'status':'success',
            'session':session.pk
        }
    except UserWarning as e:
        dc={
            'status':'fail',
            'msg':unicode(e)
        }
    except CarWashLocalModel.DoesNotExist:
        dc={
            'status':'fail',
            'msg':'zk number not registed'
        }
    except UserCarModel.DoesNotExist:
        dc={
            'status':'fail',
            'msg':'can not find match car'
        }
    return HttpResponse(json.dumps(dc),content_type="application/json")


@csrf_exempt
@hook_all
def qr(request):
    """
    不要了
    """
    customer=request.GET.get('customer')
    # local_no=request.GET.get('local')
    img = qrcode.make('http://{domain}/zk/new_session/?customer={customer}'\
                      .format(domain=settings.DOMAIN,customer=customer))
    byt=BytesIO()
    img.save(byt,'png')
    return HttpResponse(byt.getvalue(),content_type="image/png")

@csrf_exempt
@hook_all
def start(request):
    session_id=request.GET.get('session')
    try:
        session = WashSessionModel.objects.get(pk=session_id)
        session.start=timezone.now()
        session.save()
        session.order.status='using'
        session.order.save()        
        return HttpResponse(json.dumps({'status':'success'}),content_type="application/json")
    except WashSessionModel.DoesNotExist:
        return HttpResponse(json.dumps({'error':'session not exist'}),content_type="application/json")

@csrf_exempt
@hook_all
def end(request):
    session_id=request.GET.get('session')
    try:
        session = WashSessionModel.objects.get(pk=session_id)
        session.end=timezone.now()
        session.save()
        session.order.status='used'
        session.order.save()
        return HttpResponse(json.dumps({'status':'success'}),content_type="application/json")
    except WashSessionModel.DoesNotExist:
        return HttpResponse(json.dumps({'error':'session not exist'}),content_type="application/json")

@csrf_exempt
def get_code(request):
    "通过短信发验证码"
    # mobile= request.GET.get('mobile')
    # send_type = request.GET.get('type','1')
    try:
        mobile = request.GET.get('mobile')
        if not re.search('\d{11}',mobile):
            raise UserWarning,'not valid mobile number'
        mesenger = SMS()
        code = mesenger.send(mobile)
        key =str(int(time.time()))+ get_random_word()
        redis_conn.set(key,code,ex=60*2) # 2分钟过期
        
        dc={
            'status':'success',
            'code_key':key
        }
    except UserWarning as e:
        dc={
            'status':'fail',
            'msg':str(e)
        }
    return HttpResponse(json.dumps(dc),content_type="application/json")
    # if request.method=='POST':
        # args = get_argument(request)
        # # dc =urlparse.parse_qs(request.body)      
        # mobile=args.get('mobile') 
        # if mobile:
            # # Todo 通过短信发验证码
            # # fake code =1111
            # pass
        # dc ={
            # 'ret':1,
        # }
        # return HttpResponse(json.dumps(dc),content_type="application/json")

@csrf_exempt
@hook_all
def valide_sms(request):
    key = request.GET.get('code_key')
    ans =request.GET.get('ans')
    code = redis_conn.get(key)
    if str(code)==str(ans):
        redis_conn.delete(key)
        dc={
            'status':'success',
        }
    else:
        dc={
            'status':'fail'
        }
    # if request.method=='POST':
        # dc =get_argument(request)    
        # mobile=dc.get('mobile')
        # vcode=dc.get('vcode')
        # send_type=int(dc.get('type',1))
        # dc={}
        # if mobile and vcode:
            # dc['ret']= 1  # 1好像是代表成功
    return HttpResponse(json.dumps(dc),content_type="application/json")

@csrf_exempt
@hook_all
def user_login(request):
    """
    
    """
    args=get_argument(request)
    openid=args.get('openid','')
    mobile = args.get('mobile','')
    username=args.get('username','')
    passwd = args.get('passwd','')
    passwd=passwd.lower()
    
    user=None
    try:
        if openid:
            user = authenticate(openid=openid)
        elif mobile:
            user = authenticate(mobile=mobile,password=passwd)
        elif username:
            user = authenticate(username=username, password=passwd)
            
        if user is not None:
            login(request, user)
        else:
            raise UserWarning,'password not right Or user not exist'
            
        dc={
            'status':'success',
            'uid':user.pk,
            'user_session':request.session.session_key,
        }
       
    except UserWarning as e:
        dc={
            'status':'fail',
            'msg':str(e)
        }
    return HttpResponse(json.dumps(dc),content_type="application/json")
    # class LoginHandler(ApiBaseHandler):
        # @validate_sign
        # def post(self):
            # print self.validate_signature()
            # mobile = self.get_argument('mobile',None)
            # passwd = self.get_argument('passwd',None)
            # self.resp['ret'] = 0
            # try:
                # if mobile and passwd:
                    # user = _userctl.get_user_by_mobile(mobile)
                    # if user:
                        # if user['passwd'] == md5(passwd + mobile + setting.SECURE_KEY).hexdigest():
                            # self.resp['ret'] = 1
                            # self.resp['data'] = self.set_session(user)
            # except Exception ,ex:
                # print ex
                # self.resp['code'] ,self.resp['msg']= 3 , 'server error'
            # self.send()    

@csrf_exempt
@hook_all
def user_regist(request):
    try:
        if request.method=='POST':
            if request.POST.keys():
                args=request.POST
            else:
                args = json.loads( request.body)
        else:
            args=request.GET
            #args =get_argument(request)    
        mobile=args.get('mobile','')
        car_no=args.get('car_no','')
        nick = args.get('nick','')
        car_brand = args.get('car_brand',None)
        car_model = args.get('car_model',None)
        passwd = args.get('passwd')    
        openid=args.get('openid','')
        tm = mobile # str(int(time.time()*100))
        passwd=passwd.lower()
    
    # 防止 用户重复注册

        if not car_no:
            raise UserWarning,'Car No must be input'
        if not mobile or not re.search(r'\d{11}',str(mobile)):
            raise UserWarning,'Mobile Number not right'
        if not passwd:
            raise UserWarning,'Password must not null'
        car= get_or_none(UserCarModel,car_no=car_no)
        if car and car.user:
            raise UserWarning,'Car No has registed before'
        if openid:
            cus = CustomerModel.objects.filter(openid=openid)
            if cus.exists():
                raise UserWarning,'Openid has been registed'
            
        customer,is_create=CustomerModel.objects.get_or_create(mobile=mobile)
        if not is_create:
            raise UserWarning,'Mobile Number has registed before'
        
        user = User.objects.create_user(username=tm,password=passwd,)
        customer.user=user
        customer.nick_name=nick
        customer.openid=openid
        customer.save()
        
        if not car:
            car = UserCarModel.objects.create(car_no=car_no)
        
        if car_brand:
            car_brand=CarBrandModel.objects.get(pk=car_brand)
            car.car_brand=car_brand
        if car_model:
            car_model=CarModelModel.objects.get(pk=car_model)        
            car.car_model=car_model

        car.user=customer.user
        car.save()
        
        dc={
            'status':'success',
            'user':user.pk
        }
    except (UserWarning,ValueError) as e:
        dc={
            'status':'fail',
            'msg':str(e)
        }
    except CarBrandModel.DoesNotExist as e:
        dc={
            'status':'fail',
            'msg':'car_brand id is not right'
        }
    except CarModelModel.DoesNotExist as e:
        dc={
            'status':'fail',
            'msg':'car_model id is not right'
        }        
    return HttpResponse(json.dumps(dc),content_type="application/json")


def user_order(request):
    """
    获取order信息
    """
    view = request.GET.get('view','qr')
    session_id=request.GET.get('user_session')
    if session_id:
        user=session_to_user(session_id)
    else:
        user=request.user
    try:
        if view=='qr':
            # 二维码只提供注册用户的 single类型的套餐信息。。现场体验洗车，没有二维码扫描。如果号码不对，让其注册。
            dc=meals.get_user_single_meal_qr_context(user)
        else:
            dc={
                'status':'fail',
                'msg':'argument has error'
            }
    except UserWarning as e:
        dc={
            'status':'fail',
            'msg':str(e)
        }
    return HttpResponse(json.dumps(dc),content_type="application/json")

@csrf_exempt
@hook_all
def user_info(request):
    args =get_argument(request)
    openid=args.get('openid')
    
    dc={
        'msg':'not valid query info',
        'status':'error'
    }    
    
    if openid:
        cus = get_or_none(CustomerModel,openid=openid)
        if cus:
            dc = sim_dict(cus)
        else:
            dc['msg']='not valid user with openid=%s'%openid
       
    return HttpResponse(json.dumps(dc),content_type="application/json")
        

@csrf_exempt
@hook_all
def update_user_head(request):
    dc=get_argument(request)
    uid=dc.get('uid')
    head=dc.get('head')
    # uid=request.GET.get('uid')
    # head=request.GET.get('head')
    #Todo 把 head 放入 customer中
    user = User.objects.get(pk = uid)
    if not hasattr(user,'customermodel'):
        CustomerModel.objects.create(user=user)
    user.customermodel.head=head
    user.customermodel.save()
    dc={
        'status':'success'
    }
    return HttpResponse(json.dumps(dc),content_type="application/json")


def searchbrand(request):
    """
    @query : 查询字符串，如果为空，则搜索所有品牌
    @p :page number :如果为空，则为第一页，如果页码超过最后一页，则为最后一页
    @size : items per page : 每页条数
    @par : parent brand ID : 父品牌ID
    @type: brand type ：品牌类型,cb 或者mb ,默认为mb
    """
    args = get_argument(request)
    query = args.get('query','')
    p=int(args.get('p',1))
    size=int(args.get('size',30))
    par_id=int(args.get('par',0))
    brand_type=args.get('type','mb')
    # brand_type = 1 if brand_type=='mb' else 2
    filters={
        'kind':brand_type
    }
    if query:
        filters['name__icontains']=query
    if par_id:
        parent_brand=CarBrandModel.objects.get(id=par_id)
        filters['parent']=parent_brand
    query_set = CarBrandModel.objects.filter(**filters).order_by('name')
    paginator = Paginator(query_set, size)
    if p>paginator.num_pages:
        p=paginator.num_pages
    brands= paginator.page(p)
    ret={}
    for brand in brands:
        letter=brand.jp[0].upper()
        if not ret.has_key(letter):
            ret[letter]=[]
        ret[letter].append(sim_dict(brand,include=['name','jp','id']))
    dc={
        'status':'success',
        'brand_count':paginator.count,
        'page_count':paginator.num_pages,
        'p':p,
        'list':ret,
    }
    
    
    # dc = {"code": 1, "list": {}, "ret": 1, "time": 0, "msg": "ok", "total": 0}
    return HttpResponse(json.dumps(dc),content_type="application/json")
    
    
def searchcar(request):
    """TODO"""
    query = request.GET.get('query','')
    p = int(request.GET.get('p',1))
    size = int(request.GET.get('size','300'))
    brand_no = int(request.GET.get('brand'))    
    
    filters={}
    if query:
        filters['name__icontains']=query
    if brand_no:
        filters['brand_id']=brand_no
    query_set = CarModelModel.objects.filter(**filters).order_by('name')
    paginator=Paginator(query_set,size)
    if p > paginator.num_pages:
        p=paginator.num_pages
    car_models=paginator.page(p)
    
    dc={
        'status':'success',
        'list':[sim_dict(mod) for mod in car_models],
        'p':p,
        'model_count':paginator.count,
        'page_count':paginator.num_pages,
    }
    
    #dc={"code": 1, "list": [], "ret": 1, "time": 0, "msg": "ok", "total": 0}
    
    return HttpResponse(json.dumps(dc),content_type="application/json")
    # query = self.get_argument('query','')
        # p = int(self.get_argument('p',1))
        # size = int(self.get_argument('size',300))
        # brand_no = int(self.get_argument('brandno','0'))
        # result = _searchctl.carmodelinfo(query,p,size,brand_no)
        # matches = [matches['attrs'] for matches in result['matches']]

        # matches += self.get_child()
        # self.resp['list'],self.resp['total'],self.resp['time'] = matches,result['total'],result['time']
        # self.send()    

@hook_all
def car_anonymous_regist(request):
    chepai=request.GET.get('chepai')

    if not chepai:
        raise UserWarning,'must input che pai'
    car,is_create = UserCarModel.objects.get_or_create(car_no=chepai)
    
    if car.user:
        dc = {
            'status':'fail',
            'msg':'this car has been registed by registed_user'
        }
    else:
        dc={
            'status':'success',
        }

    return HttpResponse(json.dumps(dc),content_type="application/json")

@csrf_exempt
@hook_all
def washqrcode(request):
    args = get_argument(request)
    user_id = args.get('uid','')
    
    dc ={
        'ret':0
    }
    return HttpResponse(json.dumps(dc),content_type="application/json")
        
    # def get(self):
        # user_id = int(self.get_argument('uid','0'))
        # washcode = _washctl.getuser_washcode(user_id)
        # try:
            # if washcode:
                # washcode['qrcode'] = 'http://api.uacar.cn/common/qr/' + quote('http://api.uacar.cn/zk/washvalid/' + washcode['washcode'])
                # self.resp['data'] = washcode
            # else:
                # self.resp['ret'] = 0
        # except Exception,ex:
            # logger.error('getwashqrcode error:%s' , str(ex))
            # self.resp['code'],self.resp['msg'] =3, str(ex)
        # self.send()    


@csrf_exempt
@hook_all
def nearby(request):
    try:
        jd=float( request.GET.get('jd') )
        wd=float( request.GET.get('wd') )
        redius= float(request.GET.get('radius',10000))
        ls =[]
        for washlocal in CarWashLocalModel.objects.filter(status='active'):
            node_jd=float(washlocal.jd)
            node_wd=float(washlocal.wd)
            dist= distance(jd, wd, node_jd, node_wd)
            if dist < redius:
                ls.append(washlocal)
        dc={
            'status':'success',
            'locals':[sim_dict(x,include=['name','jd','wd']) for x in ls]
        }
    except ValueError as e:
        dc={
            'status':'error',
            'msg':str(e)
        }
    #args = get_argument(request)
    #query = args.get('query','')
    #p=int(args.get('p',1))
    #jd = float(args.get('jd',0.0))
    #wd = float(args.get('wd',0.0))    
    #radius = float(args.get('radius',20000.0))
    #ls = [{'jd':float(x.jd),'wd':float(x.wd)} for x in CarWashLocalModel.objects.all() if x.jd and x.wd]
    #dc ={"code": 1, "list": ls, "ret": 1, "time": 0, "msg": "ok", "total": 0}
    return HttpResponse(json.dumps(dc),content_type="application/json")

# query = self.get_argument('query','')
    # p = int(self.get_argument('p',1))
    # size = int(self.get_argument('size',30))
    # jd = float(self.get_argument('jd',0.0))
    # wd = float(self.get_argument('wd',0.0))
    # radius = float(self.get_argument('radius',20000.0))
    # result = _searchctl.washlocalinfo(query,p,size,radius,wd,jd)
    # matches = [matches['attrs'] for matches in result['matches']]
    # self.resp['list'],self.resp['total'],self.resp['time'] = matches,result['total'],result['time']
    # for attr in self.resp['list']:
        # if '@geodist' in attr:
            # attr['geodist'] = attr['@geodist']
            # del attr['@geodist']
        # attr['queuecount'] = 10 # 排队数量
        # attr['queuetime'] = attr['queuecount'] * 90  # 预计排队时长单位秒

@csrf_exempt
@hook_all
def all(request):
    dc={
        'api_type':'all'
    }
    return HttpResponse(json.dumps(dc),content_type="application/json")



def general_qr(request,content):
    """
    通用 qr，使用方式
    /qr/?content=xxxxxxx
    xxxxx必须使用base64编码
    """
    #args=get_argument(request)
    #kind=args.get('type')
    #if kind=='a':
        #content = args.get('content')
    #else:
        #content= base64.b64decode( args.get('content')).decode('utf-8')
    encode=request.GET.get('encode')
    if encode=='base64':
        content=base64.b64decode(content)
    img=qrcode.make(content)
    byt=BytesIO()
    img.save(byt,'png')
    return HttpResponse(byt.getvalue(),content_type="image/png")    

def consume(request):
    pass
    # args=get_argument(request)
    # order = args.get('order')

@csrf_exempt
@hook_all
def wx_order(request):
    """
    创建 对应的 pay_order ,例如wx_order
    
    jsapi:
    =======
    url_args: pay_type=jsapi&openid=xxxx&meal=single
    url_args: pay_type=jsapi&openid=xxxx&meal=single&chepai=川A123456
    
    """
    dc={
        'status':'error'
    }
    try:
        ip=request.META['REMOTE_ADDR']
        pay_type=request.GET['pay_type']
        openid=request.GET['openid']
        meal_name=request.GET['meal']
        
        meal=MealModel.objects.get(name=meal_name)
        coupon_no=request.GET.get('coupon')
        chepai=request.GET.get('chepai')
        
        if coupon_no:
            coupon = CouponModel.objects.get(no=coupon_no)
        else:
            coupon=None
            
        if pay_type=='jsapi':
            wx = pay.JSApiWXPay()
            params=wx.make_param(ip,openid,meal,coupon,chepai)
            # 内部微信订单号
            no=params.get('out_trade_no')
            resp = wx.unify_order(params)
            # if resp.get('return_code')=='SUCCESS' and resp.get('result_code')=='SUCCESS':
                # # 
                # wx.save_order(resp,no,meal,coupon)     
            dc ={
                'status':'success',
                }
            dc.update(wx.fetch_order_args(resp))
            
        else:
            # 其他类型，暂时没用
            customer_id= request.GET.get('customer')
            customer = User.objects.get(pk=customer_id)
            order = OrderModel.objects.create(user=customer,status='valid')
            org_url = base64.b64encode('{url_root}/zk/new_session/?order={pk}'.format(url_root=settings.URL_ROOT,pk=order.pk))
            url='{url_root}/qr/?content={content}'.format(url_root=settings.URL_ROOT,content=org_url)
            dc ={
                'status':'success',
                'order_qr_url':url,
                
            }  
    except UserCarModel.DoesNotExist:
        dc['msg']="can't find available car"
    except MultiValueDictKeyError as e:
        dc['msg']=e.message+'not found'

    except MealModel.DoesNotExist as e:
        dc['msg'] ='meal_name={meal_name} not found'.format(meal_name= meal_name)
        
    except CouponModel.DoesNotExist as e:
        dc['msg']='coupon_no=%s not found or has been used or invalid'%coupon_no
        
    return HttpResponse(json.dumps(dc),content_type="application/json") 


@csrf_exempt
@hook_all
def wxpay_reply(request):
    wx= pay.JSApiWXPay()
    xml_str = wx.reply(request)
    return HttpResponse(xml_str,content_type="text/xml")


@hook_all
def active_meal(request):
    """
    所有激活的套餐
    """
    ls=[]
    for meal in MealModel.objects.filter(status='active'):
        ls.append(sim_dict(meal))
    return HttpResponse(json.dumps(ls),content_type="application/json")

@hook_all
def washstate(request):
    session_id = request.GET.get('session')
    state_code = request.GET.get('state')
    zk_no=request.GET.get('zk')
    try:
        session = WashSessionModel.objects.get(pk=session_id)
        zk=CarWashLocalModel.objects.get(no=zk_no)
        if not state_code:
            raise UserWarning,'state must not be null'
        ZKWashLog.objects.create(zk=zk,session=session,code=state_code)
        dc={
            'status':'success'
        }
    except WashSessionModel.DoesNotExist:
        dc={
            'status':'fail',
            'msg':'session id is not right'
        }
    except CarWashLocalModel.DoesNotExist:
        dc={
            'status':'fail',
            'msg':'zk id is not right or zk have not been registed'
        }
    
    return HttpResponse(json.dumps(dc),content_type="application/json")
    
@hook_all
def zk_log(request):
    zk_no=request.GET.get('zk')
    code=request.GET.get('code')
    try:
        if not code:
            raise UserWarning,'code must not null'
        zk=CarWashLocalModel.objects.get(no=zk_no)
        ZKOtherLog.objects.create(zk=zk,code=code)
        dc={
            'status':'success'
        }
    except UserWarning as e:
        dc={
            'status':'fail',
            'msg':str(e)
        }
    except CarWashLocalModel.DoesNotExist:
        dc={
            'status':'fail',
            'msg':'zk no not exist'
        }
    
    return HttpResponse(json.dumps(dc),content_type="application/json")


def heart_beat(request):
    zk_no=request.GET.get('zk')
    try:
        zk =CarWashLocalModel.objects.get(no=zk_no)
        dc={
            'status':'success',
            'expire':60*2
        }
    except CarWashLocalModel.DoesNotExist:
        dc={
            'status':'fail',
            'msg':'zk id is not right or zk have not been registed'
        }        
    
    return HttpResponse(json.dumps(dc),content_type="application/json")

def check_order_key(request):
    order_key=request.GET.get('order_key')
    if order_key:
        dc = meals.check_order_key(order_key)
        dc['status']='success'
    else:
        dc={
            'status':'error',
            'msg':'need order_key'
        }
    return HttpResponse(json.dumps(dc),content_type="application/json")

def session_check(request):
    session_id= request.GET.get('session')
    try:
        session=WashSessionModel.objects.get(pk=session_id)
        log = ZKWashLog.objects.filter(session=session).order_by('-update_at').first()
        if log:
            dc={
                'status':'success',
                'code':log.code,
                'update':log.update_at.strftime('%Y/%m/%d %H:%M:%S') 
            }
        else:
            dc={
                'status':'fail',
                'msg':'no related log'
            }
    except WashSessionModel.DoesNotExist:
        dc={
            'status':'error',
            'msg':'session id not exist'
        }
    return HttpResponse(json.dumps(dc),content_type="application/json")

def zk_last_chepai(request):
    zk_no=request.GET.get('zk')
    chepai = redis_conn.get('__last_car_no_'+zk_no)
    if chepai:
        dc={
            'status':'success',
            'chepai':chepai
        }
    else:
        dc={
            'status':'fail',
            'chepai':'zk number not right or chepai has expired(5 minutes)'
        }
    return HttpResponse(json.dumps(dc),content_type="application/json")

def del_user(request):
    try:
        openid =request.GET.get('openid')
        user=User.objects.get(customermodel__openid=openid)
        user.delete()
        dc={
            'status':'success'
        }
    except User.DoesNotExist:
        dc={
            'status':'fail',
            'msg':'user not exist with openid=%s'%openid
        }
    return HttpResponse(json.dumps(dc),content_type="application/json")
    
